<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :close-on-click-modal="false" @close="close" width="1050px">
    <div class="form-box new_form_box">
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="100px" class="demo-ruleForm">
        <div style="margin:0 0 10px ;">
          <formSubTitVue title="基础信息"></formSubTitVue>
        </div>
        <el-form-item label="收支类型" prop="type">
          <el-select :disabled="isFromIndex" v-model="form.type" placeholder="请选择收支类型">
            <el-option v-for="dict in type" :key="dict.value" :label="dict.name" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="账单类型" prop="bookType">
          <el-select @change="billChange" v-model="form.bookType" filterable placeholder="请选择账单类型">
            <el-option v-for="bill in billTypeListNew" :key="bill.id" :label="bill.bookType" :value="bill.bookType" />
          </el-select>
        </el-form-item>

        <el-form-item label="对方名称" prop="duifangmingcheng">
          <el-input v-model="form.duifangmingcheng" placeholder="请输入对方名称" />
        </el-form-item>
        <el-form-item label="对方账户" prop="duifangzhanghu">
          <el-input v-model="form.duifangzhanghu" placeholder="请输入对方账户" />
        </el-form-item>
        <el-form-item label="本方名称" prop="benfangmingcheng">
          <el-input v-model="form.benfangmingcheng" placeholder="请输入本方名称" />
        </el-form-item>
        <el-form-item label="本方账户" prop="benfangzhanghu">
          <el-input v-model="form.benfangzhanghu" placeholder="请输入本方账户" />
        </el-form-item>
        <el-form-item label="金额" prop="jine">
          <el-input v-model="form.jine" placeholder="请输入金额" />
        </el-form-item>

        <el-form-item label="经办人" prop="jingbanren">
          <el-input v-model="form.jingbanren" placeholder="请输入经办人" />
        </el-form-item>
        <el-form-item label="复核人" prop="fuheren">
          <el-input v-model="form.fuheren" placeholder="请输入复核人" />
        </el-form-item>

        <div v-if="billTypeConfig&&billTypeConfig.length">
          <div style="margin: 10px 0;">
            <formSubTitVue title="自定义信息"></formSubTitVue>
          </div>
          <span v-for="custom in billTypeConfig" :key="custom.id">
            <el-form-item :label="custom.name" :prop="custom.key" v-if="custom.isShow">
              <el-input v-model="form[custom.key]" :placeholder="`请填写${custom.name}`" />
            </el-form-item>
          </span>
        </div>
        <div style="margin: 10px 0;">
          <formSubTitVue title="其他信息"></formSubTitVue>
        </div>
        <el-form-item label-width="50px" label="明细" prop="mingxi" class="row">
          <el-input v-model="form.mingxi" type="textarea" placeholder="账单详细说明" :rows="4" />
        </el-form-item>
        <el-form-item label-width="50px" label="备注" prop="beizhu" class="row">
          <el-input v-model="form.beizhu" type="textarea" placeholder="账单详细说明" :rows="4" />
        </el-form-item>

        <el-form-item label-width="80px" label="图片附件" class="row">
          <el-upload :action="uploadImgUrl" :file-list="imgShowList" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-exceed="uploadNumber" :multiple="true" :drag="true" :on-success="handleUploadSuccess" :limit="50" :on-remove="handleRemove" :headers="headers">
            <div class="uploadbg">
              <img src="https://imgage.maimaihao.com/yuduhulian/erp/static/icon/uploadbg.png" alt="">
              <br />
              <span>上传图片</span>
            </div>
          </el-upload>
          <div style="width: 100px;">
            <saomaUpload @success="saomaEnd">
              <el-button type="primary" plain>扫码上传</el-button>
            </saomaUpload>
          </div>
        </el-form-item>

        <div class="center">
          <el-button @click="close()">取消</el-button>
          <el-button type="primary" @click="submitForm('form')" v-loading="loading">提交</el-button>
        </div>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from "@/utils/auth";
import jizhangbenApi from "@/api/financeCenter/jizhangben.js";
import saomaUpload from "../../../../components/upload/saomaUpload.vue";
export default {
  name: "addFina",
  props: ["billTypeList"],
  components:{saomaUpload},
  data() {
    return {
      dialogVisible: false,
      loading: false,
      type: [
        {
          name: "收入",
          value: 1,
        },
        {
          name: "支出",
          value: 2,
        },
      ],
      billTypeConfig: null, //自定义字段配置
      title: "新增日常收支",
      isEdit: false,
      uploadImgUrl: "",
      imgShowList: [],
      newImages: [],
      imgFileList: [],
      // 表单参数
      form: {
        type: "",
        bookType: "",
        duifangmingcheng: "",
        duifangzhanghu: "",
        benfangmingcheng: "",
        benfangzhanghu: "",
        jine: "",
        jingbanren: "",
        fuheren: "",
        mingxi: "",
        beizhu: "",
        img: "",
        field1: "",
        field2: "",
        field3: "",
        field4: "",
        field5: "",
        field6: "",
        field7: "",
        field8: "",
        field9: "",
        field10: "",
      },
      headers: {},
      rules: {
        type: [
          { required: true, message: "请选择收支类型", trigger: "change" },
        ],
        bookType: [
          { required: true, message: "请选择账单类型", trigger: "change" },
        ],
        jine: [{ required: true, message: "请输入金额", trigger: "blur" }],
      },
      isFromIndex: false,
      billTypeListNew: [],
    };
  },
  created() {
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  methods: {
    // 打开弹窗
    async open(flag, data) {
      this.isFromIndex = false;
      this.newImages = [];
      this.imgShowList = [];
      this.imgFileList = [];
      this.billTypeConfig = null;
      this.form.id = null;
      if (flag == "edit") {
        this.title = "修改日常收支";
        this.isEdit = true;
        this.handleUpdate(data);
      } else {
        if (flag == 1 || flag == 2) {
          this.form.type = flag;
          this.isFromIndex = true;
        }
        this.isEdit = false;
      }
      this.dialogVisible = true;
      if (this.billTypeList && this.billTypeList.length) {
        this.billTypeListNew = [...this.billTypeList];
      } else {
        await this.getTypeList();
      }
    },
    // 奇特图片扫码上传
    saomaEnd(e) {
      console.log("%c Line:189 🍑 e", "color:#33a5ff", e);
      if (e && e.length) {
        this.imgFileList = this.imgFileList.concat(e);
        this.imgShowList = this.imgShowList.concat(e);
      }
    },
    // 重置
    reset() {
      this.$refs.form.resetFields();
    },
    // // 获取账单类型列表
    async getTypeList() {
      const res = await jizhangbenApi.getTypeList();
      this.billTypeListNew = res.rows;
      if (res.rows.length == 0) {
        // this.$message.error("请先配置账单类型！");

        this.$confirm("没有配置账单类型，点击确认前往配置", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.close();
            if (this.$route.name == "Jizhangben") {
              this.$emit("openSet");
            } else {
              this.$router.push({
                name: "Jizhangben",
                query: {
                  type: "openSet",
                },
              });
            }
          })
          .catch(() => {});
      }
    },
    // 账单类型改变
    billChange(val, flag) {
      // let ioType = Number(this.form.iotype)
      // let billType = Number(this.form.billType)
      // this.$refs.form.resetFields();
      // this.form.iotype = ioType
      // this.form.billType = billType
      this.billTypeListNew.forEach((item) => {
        if (item.bookType == val && item.fields) {
          this.rules = {
            type: [
              { required: true, message: "请选择收支类型", trigger: "change" },
            ],
            bookType: [
              { required: true, message: "请选择账单类型", trigger: "change" },
            ],
            jine: [{ required: true, message: "请输入金额", trigger: "blur" }],
          };
          let arr = JSON.parse(item.fields);
          const showArr = [];
          if (arr && arr.length) {
            arr.forEach((r) => {
              if (r.isShow) {
                if (flag != "edit") {
                  this.form[r.key] = "";
                }

                showArr.push({ ...r });
                if (r.isMust) {
                  this.rules[r.key] = [
                    {
                      required: true,
                      message: `请填写${r.name}`,
                      trigger: "blur",
                    },
                  ];
                }
              }
            });
            this.$nextTick(() => {
              this.billTypeConfig = showArr;
            });
          }
        }
      });
    },

    /** 查询详情进行回显 */
    handleUpdate(row) {
      const id = row.id || null;
      jizhangbenApi.tallyBookInfoById(id).then((res) => {
        this.form = { ...res.data };
        if (this.form.img) {
          this.imgShowList = JSON.parse(this.form.img);
          this.imgFileList = JSON.parse(this.form.img);
        }
        this.billChange(this.form.bookType, "edit");
      });
    },
    submitForm(formName) {
      this.$refs["" + formName].validate((valid) => {
        if (valid) {
          // 拼接新上传的图片
          if (this.newImages && this.newImages.length) {
            let newArr = [];
            this.newImages.forEach((img) => {
              newArr.push({
                name: img.name,
                url: img.response.data.filePath,
              });
            });
            this.form.img = JSON.stringify(this.imgFileList.concat(newArr));
          } else {
            this.form.img = JSON.stringify(this.imgFileList);
          }
          if (this.isEdit) {
            // 编辑
            jizhangbenApi.editTallyBook(this.form).then((res) => {
              this.$message.success(res.msg);
              this.close();
              this.$parent.search();
            });
          } else {
            // 新增
            //console.log(this.form);
            jizhangbenApi.addTallyBook(this.form).then((res) => {
              this.$message.success(res.msg);
              this.close();
              this.$emit("addSuccess");
            });
          }
        } else {
          this.$alert("请填写完整！");
        }
      });
    },
    // 详情图片上传成功
    handleUploadSuccess(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 详情图片删除
    handleRemove(response, fileList, file) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList.splice(key, 1); //回显的图片
        }
      });
      this.newImages.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages.splice(key, 1); //新上传的图片
        }
      });
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传50张图片");
    },
    close() {
      this.dialogVisible = false;
      this.reset();
    },
  },
};
</script>
<style scoped lang="css">
.center {
  text-align: center;
}

/deep/ .el-upload-dragger {
  width: 150px;
  height: 150px;
}
</style>
